package com.xy.webadmin.app.schedule;

import com.xy.webadmin.app.constant.MqttConstants;
import com.xy.webadmin.app.service.MqttClientManager;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageHandler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * MQTT连接健康检查定时任务 - 基于Spring Integration MQTT
 *
 * @author xiaoyue
 * @date 2025-07-10
 */
@Slf4j
@Component
public class MqttHealthSchedule {

    @Autowired
    private MqttClientManager mqttClientManager;
    
    // 跟踪连接状态的缓存
    private final Map<Long, Boolean> connectionStatusCache = new ConcurrentHashMap<>();
    
    /**
     * 每5分钟执行一次MQTT连接健康检查
     */
    @Scheduled(fixedDelay = MqttConstants.Schedule.HEALTH_CHECK_INTERVAL)
    public void checkMqttConnections() {
        log.info("执行定时MQTT连接健康检查");
        
        // 获取所有公司的配置
        mqttClientManager.getAllConfigs().forEach(config -> {
            Long configId = config.getId();
            Long companyId = config.getCompanyId();
            
            try {
                MessageHandler handler = mqttClientManager.getMqttOutboundHandler(companyId, configId);
                if (handler instanceof MqttPahoMessageHandler) {
                    MqttPahoMessageHandler mqttHandler = (MqttPahoMessageHandler) handler;
                    
                    // 检查连接状态
                    boolean isConnected = mqttHandler.isRunning();
                    
                    // 记录连接状态变化
                    Boolean previousStatus = connectionStatusCache.get(configId);
                    if (previousStatus == null || previousStatus != isConnected) {
                        if (isConnected) {
                            log.info("MQTT连接已恢复, configId: {}, companyId: {}", configId, companyId);
                        } else {
                            log.warn("MQTT连接已断开, configId: {}, companyId: {}", configId, companyId);
                            
                            // 尝试重新初始化连接
                            try {
                                mqttClientManager.registerMqttClient(config);
                                log.info("已尝试重新注册MQTT客户端, configId: {}", configId);
                            } catch (Exception e) {
                                log.error("重新注册MQTT客户端失败, configId: {}", configId, e);
                            }
                        }
                    }
                    
                    connectionStatusCache.put(configId, isConnected);
                }
            } catch (Exception e) {
                log.error("检查MQTT连接状态失败, configId: {}", configId, e);
            }
        });
    }
    
    /**
     * 应用关闭前断开所有MQTT连接
     */
    @PreDestroy
    public void shutdown() {
        log.info("应用关闭，断开所有MQTT连接");
        mqttClientManager.disconnectAll();
    }
} 